<template>
  <a-button
    type="link"
    style="padding: 4px 6px"
    @click="onClick"
    :loading="loading"
    :disabled="hasEditing && !editing"
  >
    {{ editing ? '保存' : '编辑' }}
  </a-button>
</template>
<script setup>
import { useDbType } from '@/views/db-management/provide-context.js'

import { computed } from 'vue'
import { useVModel } from '@vueuse/core'
import { Form, message as Message } from 'ant-design-vue'
import {
  useDataSourceManager,
  useDataSource,
  // useGroupId,
  useLockForInUse,
} from './provide-context.js'
import { createFolder, updateFileInfo } from '@/api/db.js'
/**
 * 外部参数
 */
let props = defineProps({
  editing: { type: Boolean, default: () => false },
  loading: { type: Boolean, default: () => false },
  data: { type: Object, required: true },
  rules: { type: Object, default: () => ({}) },
})
/**
 * 事件定义
 */
let emit = defineEmits(['update:editing', 'update:loading', 'submit'])
/**
 * 双向绑定
 */
let editing = useVModel(props, 'editing', emit)
let loading = useVModel(props, 'loading', emit)
/**
 * 全局
 */
let { update } = useDataSourceManager()
let dataSource = useDataSource()
// let groupId = useGroupId()
let lockForInUse = useLockForInUse()
let dbType = useDbType()
/**
 * 校验相关
 */
let useForm = Form.useForm
let { validate } = useForm(props.data, props.rules)
/**
 * 整体有没有在编辑状态
 */
let hasEditing = computed(() =>
  dataSource.value.some(({ editing }) => editing === true),
)
/**
 * 锁标识
 */
let lockSymbol = Symbol('edit')
/**
 * 操作事件
 */
async function onClick() {
  if (editing.value) {
    loading.value = true
    try {
      emit('submit')
      await validate()
      if (props?.data?.new) {
        await createFolder(
          {
            newFolderName: props?.data?.dataName,
            parentId: props?.data?.categoryId, // new add
            fileNote: props?.data?.note,
          },
          dbType,
        )
      } else {
        await updateFileInfo(
          {
            id: props?.data?.dataId,
            fileName: props?.data?.dataName,
            fileNote: props?.data?.note,
          },
          dbType,
        )
      }
      await update()
      editing.value = false
      lockForInUse.value = null
      Message.success(`${props?.data?.dataName}发布成功!`)
    } catch (e) {
      Message.error(`${props?.data?.dataName}发布失败!`)
    }
    loading.value = false
  } else {
    editing.value = true
    lockForInUse.value = lockSymbol
  }
}
</script>
